package com.junsi.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.junsi.bean.Approve;
import com.junsi.bean.ApproveRole;
import com.junsi.bean.ApproveTail;
import com.junsi.bean.Audits;
import com.junsi.bean.Salestage;
import com.junsi.bean.Staff;
import com.junsi.service.ApproveRoleService;
import com.junsi.service.ApproveService;
import com.junsi.service.ApproveTailService;
import com.junsi.service.AuditsService;
import com.junsi.service.SalestageService;
import com.junsi.service.StaffSerivce;
import com.junsi.util.DownlaodExcel;
import com.junsi.util.DownloadUtil;
import com.junsi.util.FileUtil;
import com.junsi.util.InteractiveUtil;
import com.junsi.util.PageUtil;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("/audits")
public class AuditsController {
	@Autowired
	public AuditsService auditsService;
	@Autowired
	private ApproveService approveService;
	@Autowired
	private ApproveTailService apperoveTailService;
	@Autowired
	private StaffSerivce staffSerivce;
	@Autowired
	private ApproveRoleService approveRoleService;// 审批角色表
	@Autowired
	private SalestageService salestageService;
	Logger logger = Logger.getRootLogger();

	@RequestMapping("/download") // 文件下载
	public void download(String id, String vlaues, HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		Approve approve = approveService.findById(Integer.valueOf(id));
		Audits audits = auditsService.findById(Integer.valueOf(approve.getAuditId()));
		if ("0".equals(vlaues)) {// 上传证明
			DownloadUtil.download(audits.getSupplementals(), response, request);
		} else if ("1".equals(vlaues)) {// 上传证明2
			DownloadUtil.download(audits.getSupplementalsTwo(), response, request);
		}
	}

	@RequestMapping("/insert") // 审核表 approveCharacter :提交审批表人
	public ModelAndView insert(Audits audits, String apperoveTail, String approveCharacter,
			HttpServletResponse response, HttpServletRequest request, @RequestParam("file") CommonsMultipartFile file,
			@RequestParam("file2") CommonsMultipartFile file2) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		if (!file.isEmpty()) {
			String picture1 = FileUtil.Uploadfile(file);
			if ("上传失败".equals(picture1)) {
				modelAndView.addObject("reult", "失败");
				return modelAndView;
			}
			audits.setSupplementals(picture1);
		} else {
			audits.setSupplementals("没有文件!");
		}
		if (!file.isEmpty()) {
			String picture = FileUtil.Uploadfile(file2);
			if ("上传失败".equals(picture)) {
				modelAndView.addObject("reult", "失败");
				return modelAndView;
			}
			audits.setSupplementalsTwo(picture);
		} else {
			audits.setSupplementalsTwo("没有文件!");
		}
		boolean result = false;
		boolean r = false;
		if (apperoveTail != null && !"".equals(apperoveTail)) {
			if (audits.getAssumePercentage() != null && !"".equals(audits.getAssumePercentage().trim())) {
				String assumePercentage = audits.getAssumePercentage() + "%";
				audits.setAssumePercentage(assumePercentage);
			}
			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
			String dateSubmitTime = format.format(date);
			System.out.println(dateSubmitTime);
			audits.setSubmitTime(dateSubmitTime);
			ApproveTail approveTails = new ApproveTail();
			ApproveRole approveRole = approveRoleService.findById(Integer.valueOf(apperoveTail));
			approveTails.setApproverID(approveRole.getApprover());
			approveTails.setApproveType(approveRole.getTypeObject());
			approveTails.setApproveRoleId(approveRole.getApproveRoleId().toString());
			apperoveTailService.insert(approveTails);
			if (approveCharacter != null && !"".equals(approveCharacter.trim())) {
				List<Staff> staffs = staffSerivce.findByAll();// 管理员填写审批表
				for (Staff s : staffs) {
					String id = s.getStaff_id().toString();
					if (id.equals(approveCharacter)) {
						audits.setSenderId(s.getStaff_name());
					}
				}
			} else {
				Staff staff = ((Staff) request.getSession().getAttribute("staff"));
				audits.setSenderId(staff.getStaff_name());
			}
			audits.setApprovalState("待审批");
			List<Approve> approve = new ArrayList<Approve>();
			ApproveTail approveTail = (ApproveTail) this.apperoveTailService.findById(approveTails.getApproveId());// 审批跟踪id
			audits.setApproveTailId(approveTail.getApproveType());
			result = this.auditsService.insert(audits);

			if ((approveTail.getApproverId() != null) || ("".equals(approveTail.getApproverId()))) {
				String[] array = approveTail.getApproverId().split(",");
				for (int i = 0; i < array.length; i++) {
					Approve a = new Approve();
					a.setSenderId(audits.getSenderId());// 审批人
					a.setApproverID(array[i]);
					a.setApproveCondition("未批准");
					a.setApproveRoleId(approveTails.getApproveId().toString());// 审批跟踪id
					a.setAuditId(audits.getAuditId().toString());
					approve.add(i, a);
				}
			}
			r = this.approveService.batchSaveAudits(approve);
			if ((result) && (r)) {
				modelAndView.addObject("show", "审核表提交成功!");
			} else {
				modelAndView.addObject("show", "审核表提交失败!");
			}
		} else {
			modelAndView.addObject("show", "审批部门不可为空!");
		}
		modelAndView.setViewName("forward:/audits/count.action?pageSize=0");
		return modelAndView;
	}

	@RequestMapping("/submitContract") // 领导审批
	public ModelAndView submitContract(Approve approve, HttpServletResponse response, HttpServletRequest request)
			throws Exception {
		boolean result = false;
		if (approve.getApproveid() != null) {
			this.approveService.updateRemarks(approve);
			Approve approveData = (Approve) this.approveService.findById(approve.getApproveid());
			ApproveTail approveTail = this.apperoveTailService.findapprove(approveData.getApproveRoleId());
			String r = approve.getApproveCondition();
			String approver = null;
			Approve approve2 = new Approve();
			Audits audits = new Audits();// ------contractApprove2
			ApproveTail approveTail2 = new ApproveTail();
			approveTail2.setApproveID(approveTail.getApproveId());
			approve2.setApproveRoleId(approveTail.getApproveId().toString());
			Integer auditId = Integer.valueOf(approveData.getAuditId());
			audits.setAuditId(auditId);
			if (r.equals("不批准")) {
				approve2.setApproveCondition("不批准");
				audits.setApprovalState("审批失败");
				this.approveService.batchUpdate(approve2);// 不批准
				approveTail2.setApproverID("");
				this.auditsService.update(audits);// =============
				result = this.apperoveTailService.updateApproverID(approveTail2);

			}
			if (r.equals("已批准")) {
				String[] approverId = approveTail.getApproverId().split(",");
				if ((approverId.length == 1) && (!"".equals(approverId[0]))) {
					approve2.setApproveCondition("已批准");
					audits.setApprovalState("已批准");
					approveTail2.setApproverID("");
					approve2.setApproveid(approveData.getApproveid());
					this.approveService.update(approve2);
					this.auditsService.update(audits);
					approveTail2.setApproveID(approveTail.getApproveId());
					result = this.apperoveTailService.updateApproverID(approveTail2);
				}
				if (approverId.length == 2) {
					approver = approverId[1];
					approve2.setApproveCondition("已批准");
					audits.setApprovalState("审批中");
					approve2.setApproveid(approveData.getApproveid());
					this.approveService.update(approve2);
					approveTail2.setApproveID(approveTail.getApproveId());
					approveTail2.setApproverID(approver);
					this.auditsService.update(audits);
					result = this.apperoveTailService.updateApproverID(approveTail2);
				} else if (approverId.length > 2) {
					for (int i = 1; i < approverId.length; i++) {
						if (i > 1) {
							approver = approver + "," + approverId[i];
						} else {
							approver = approverId[i];
						}
					}
					approve2.setApproveCondition("已批准");
					audits.setApprovalState("审批中");
					approve2.setApproveid(approveData.getApproveid());
					this.approveService.update(approve2);
					approveTail2.setApproveID(approveTail.getApproveId());
					approveTail2.setApproverID(approver);
					this.auditsService.update(audits);
					result = this.apperoveTailService.updateApproverID(approveTail2);
				}

			}
		}
		ModelAndView modelAndView = new ModelAndView();
		if (result) {
			modelAndView.addObject("show", "审批成功!");
		} else {
			modelAndView.addObject("show", "审批失败!");
		}
		modelAndView.setViewName("forward:/audits/count.action");// --------
		return modelAndView;
	}

	@RequestMapping("/pageFindnoapprove") // 未批准分页查询
	public void pageFindnoapprove(PageUtil page, String condition, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		Staff staff = ((Staff) request.getSession().getAttribute("staff"));
		page.setPageSize(5);
		List<Approve> approvepages;
		if (condition != null && !"".equals(condition)) {
			Integer count = approveService.timeFindCountAudits(staff.getStaff_name(), condition.trim());
			page.setRowCount(count);
			approvepages = approveService.timeFindByAllAudits(staff.getStaff_name(), page, condition.trim());
		} else {
			Integer count = approveService.findCountAudits(staff.getStaff_name());//
			page.setRowCount(count);
			approvepages = approveService.findByAllAudits(staff.getStaff_name(), page);// 审批
		}
		List<Audits> auditsarray = auditsService.listAll();// 合同审批

		String applicant = null;// 申请名称
		String rPerson = null;// 负责人
		String auditType = null;// 申请类型
		String pCategory = null;// 产品类别
		String assumePercentage = null;// 承担百分比

		/*
		 * String effectTimeStart=null;//生效时间初 String effectTimeFinish=null;//生效时间末
		 */
		List<Map<String, String>> array = new ArrayList<Map<String, String>>();
		for (Approve approvepag : approvepages) {
			Map<String, String> map = new HashMap<String, String>();
			List<Staff> staffs = staffSerivce.findByAll();
			for (Staff s : staffs) {
				String id = s.getStaff_id().toString();
				if (id.equals(approvepag.getApproverID())) {
					approvepag.setApproverID(s.getStaff_name());
				}
			}
			for (Audits audits : auditsarray) {
				String acontractApproveid = audits.getAuditId().toString();
				if (approvepag.getAuditId().equals(acontractApproveid)) {
					List<Salestage> salestages = salestageService.listAll();
					for (Salestage arraySalestage : salestages) {
						String salestage = arraySalestage.getSaleStageId().toString();
						if (salestage.equals(audits.getpCategory())) {
							audits.setpCategory(arraySalestage.getSaleStageName());
						}
					}
					approvepag.setSenderId(audits.getSenderId());// 发送人
					applicant = audits.getApplicant();// 申请名称
					rPerson = audits.getrPerson();// 负责人
					auditType = audits.getAuditType();// 申请类型
					pCategory = audits.getpCategory();// 产品类别
					assumePercentage = audits.getAssumePercentage();// 承担百分比

				}
			}
			map.put("Approvers", approvepag.getApproverID());// 审批人
			map.put("approveId", approvepag.getApproveid().toString());// 編號
			map.put("approvalState", approvepag.getApproveCondition());// 审批状态
			map.put("applicant", applicant==null?"":applicant);// 申请名称
			map.put("rPerson", rPerson==null?"":rPerson);// 负责人
			map.put("auditType", auditType==null?"":auditType);// 申请类型
			map.put("pCategory", pCategory==null?"":pCategory);// 产品类别
			map.put("assumePercentage", assumePercentage==null?"":assumePercentage);// 承担百分比
			array.add(map);
		}
		response.setContentType("text/json; charset=UTF-8");
		InteractiveUtil.WriteJsonForPage(array, page, response);

	}

	@RequestMapping("/alreadyapproveAll") // 以批准,不审批查询分页
	public void alreadyapproveAll(PageUtil page, String condition, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		Staff staff = ((Staff) request.getSession().getAttribute("staff"));
		page.setPageSize(5);
		List<Approve> approvepages;
		if (condition != null && !"".equals(condition)) {
			Integer count = approveService.timeFindCountAuditsOne(staff.getStaff_name(), condition.trim());
			page.setRowCount(count);
			approvepages = approveService.timeFindByAllAuditsOne(staff.getStaff_name(), page, condition.trim());
		} else {
			Integer count = approveService.findCountAuditsOne(staff.getStaff_name());//
			page.setRowCount(count);
			approvepages = approveService.findByAllAuditsOne(staff.getStaff_name(), page);// 审批
		}
		List<Audits> auditsarray = auditsService.listAll();// 合同审批
		String applicant = null;// 申请名称
		String rPerson = null;// 负责人
		String auditType = null;// 申请类型
		String pCategory = null;// 产品类别
		String assumePercentage = null;
		// 承担百分比
		/*
		 * String effectTimeStart=null;//生效时间初 String effectTimeFinish=null;//生效时间末
		 */
		List<Map<String, String>> array = new ArrayList<Map<String, String>>();
		for (Approve approvepag : approvepages) {
			Map<String, String> map = new HashMap<String, String>();
			List<Staff> staffs = staffSerivce.findByAll();
			for (Staff s : staffs) {
				String id = s.getStaff_id().toString();
				if (id.equals(approvepag.getApproverID())) {
					approvepag.setApproverID(s.getStaff_name());
				}
			}
			for (Audits audits : auditsarray) {
				String acontractApproveid = audits.getAuditId().toString();
				if (approvepag.getAuditId().equals(acontractApproveid)) {
					if (approvepag.getAuditId().equals(acontractApproveid)) {
						List<Salestage> salestages = salestageService.listAll();
						for (Salestage arraySalestage : salestages) {
							String salestage = arraySalestage.getSaleStageId().toString();
							if (salestage.equals(audits.getpCategory())) {
								audits.setpCategory(arraySalestage.getSaleStageName());
							}
						}
						approvepag.setSenderId(audits.getSenderId());// 发送人
						applicant = audits.getApplicant();// 申请名称
						rPerson = audits.getrPerson();// 负责人
						auditType = audits.getAuditType();// 申请类型
						pCategory = audits.getpCategory();// 产品类别
						assumePercentage = audits.getAssumePercentage();// 承担百分比
					}
				}
			}
			map.put("Approvers", approvepag.getApproverID());// 审批人
			map.put("approveId", approvepag.getApproveid().toString());// 編號
			map.put("approvalState", approvepag.getApproveCondition());// 审批状态
			map.put("applicant", applicant==null?"":applicant);// 申请名称
			map.put("rPerson", rPerson==null?"":rPerson);// 负责人
			map.put("auditType", auditType==null?"":auditType);// 申请类型
			map.put("pCategory", pCategory==null?"":pCategory);// 产品类别
			map.put("assumePercentage", assumePercentage==null?"":assumePercentage);// 承担百分比
			array.add(map);
		}
		response.setContentType("text/json; charset=UTF-8");
		InteractiveUtil.WriteJsonForPage(array, page, response);
	}

	@RequestMapping("/findApproveAmong") // 领导审批中查询
	public void findApproveAmong(PageUtil page, String condition, HttpServletResponse response,
			HttpServletRequest request) throws Exception {

		Staff staff = ((Staff) request.getSession().getAttribute("staff"));
		page.setPageSize(5);
		List<Approve> approves;
		if (condition != null && !"".equals(condition)) {
			Integer count = approveService.timeTApproveCountAudits(staff.getStaff_id().toString(), condition.trim());
			page.setRowCount(count);
			approves = approveService.timeTApproveAuditsOne(staff.getStaff_id().toString(), page, condition.trim());
		} else {
			Integer count = approveService.tApproveCountAudits(staff.getStaff_id().toString());//
			page.setRowCount(count);
			approves = approveService.tApproveAuditsOne(staff.getStaff_id().toString(), page);
		}
		List<Audits> atsArray = auditsService.listAll();// 合同审批
		List<Map<String, String>> array = new ArrayList<Map<String, String>>();
		if (approves != null) {

			/*
			 * String effectTimeStart=null;//生效时间初 String effectTimeFinish=null;//生效时间末
			 */ String applicant = null;// 申请名称
			String rPerson = null;// 负责人
			String auditType = null;// 申请类型
			String pCategory = null;// 产品类别
			String assumePercentage = null;// 承担百分比

			for (Approve approvepag : approves) {// 用戶所要審核的表
				Map<String, String> map = new HashMap<String, String>();
				ApproveTail apperoveTails = apperoveTailService.findapprove(approvepag.getApproveRoleId());// 审核跟踪
				String[] arrayname = apperoveTails.getApproverId().split(",");
				for (Audits audits : atsArray) {
					String audit = audits.getAuditId().toString();// 合同审批id
					if (approvepag.getAuditId().equals(audit)) {
						List<Salestage> salestages = salestageService.listAll();
						for (Salestage arraySalestage : salestages) {
							String salestage = arraySalestage.getSaleStageId().toString();
							if (salestage.equals(audits.getpCategory())) {
								audits.setpCategory(arraySalestage.getSaleStageName());
							}
						}
						applicant = audits.getApplicant();// 申请名称 ///
						rPerson = audits.getrPerson();// 负责人
						auditType = audits.getAuditType();// 申请类型
						pCategory = audits.getpCategory();// 产品类别
						assumePercentage = audits.getAssumePercentage();// 承担百分比
						break;
					}
				}
				map.put("senderId", approvepag.getSenderId());// 发送人
				map.put("approveId", approvepag.getApproveid().toString());// 編號
				map.put("approvalState", approvepag.getApproveCondition());// 审批状态
				map.put("applicant", applicant==null?"":applicant);// 申请名称
				map.put("rPerson", rPerson==null?"":rPerson);// 负责人
				map.put("auditType", auditType==null?"":auditType);// 申请类型
				map.put("pCategory", pCategory==null?"":pCategory);// 产品类别
				map.put("assumePercentage", assumePercentage==null?"":assumePercentage);// 承担百分比
				if (arrayname[0].equals(approvepag.getApproverID())) {
					array.add(map);
				}
			}

		}
		if(array.size()==0 && page.getPageNum()==1) {
			page.setPageCount(0);
		}
		response.setContentType("text/json; charset=UTF-8");
		InteractiveUtil.WriteJsonForPage(array, page, response);
	}

	@RequestMapping("/findAllApproveCondition") // 以批准,不审批查询所有分页//----------------
	public void findAllApproveCondition(PageUtil page, String condition, HttpServletResponse response,
			HttpServletRequest request) throws Exception {

		page.setPageSize(5);
		List<Approve> approvepages;
		if (condition != null && !"".equals(condition)) {
			Integer count = approveService.timefindCountAllApproveCondition(condition.trim());//
			page.setRowCount(count);
			approvepages = approveService.timefindAllApproveCondition(page, condition.trim());// 审批
		} else {
			Integer count = approveService.findCountAllApproveCondition();//
			page.setRowCount(count);
			approvepages = approveService.findAllApproveCondition(page);// 审批
		}
		List<Audits> auditsarray = auditsService.listAll();// 合同审批
		String applicant = null;// 申请名称
		String rPerson = null;// 负责人
		String auditType = null;// 申请类型
		String pCategory = null;// 产品类别
		String assumePercentage = null;// 承担百分比
		List<Map<String, String>> array = new ArrayList<Map<String, String>>();
		for (Approve approvepag : approvepages) {
			Map<String, String> map = new HashMap<String, String>();
			List<Staff> staffs = staffSerivce.findByAll();
			for (Staff s : staffs) {
				String id = s.getStaff_id().toString();
				if (id.equals(approvepag.getApproverID())) {
					approvepag.setApproverID(s.getStaff_name());
				}
			}
			for (Audits audits : auditsarray) {
				String acontractApproveid = audits.getAuditId().toString();
				if (approvepag.getAuditId().equals(acontractApproveid)) {
					List<Salestage> salestages = salestageService.listAll();
					for (Salestage arraySalestage : salestages) {
						String salestage = arraySalestage.getSaleStageId().toString();
						if (salestage.equals(audits.getpCategory())) {
							audits.setpCategory(arraySalestage.getSaleStageName());
						}
					}
					approvepag.setSenderId(audits.getSenderId());// 发送人
					applicant = audits.getApplicant();// 申请名称
					rPerson = audits.getrPerson();// 负责人
					auditType = audits.getAuditType();// 申请类型
					pCategory = audits.getpCategory();// 产品类别
					assumePercentage = audits.getAssumePercentage();// 承担百分比

				}
			}
			map.put("senderId", approvepag.getSenderId());// 发送人
			map.put("approveId", approvepag.getApproveid().toString());// 編號
			map.put("Approvers", approvepag.getApproverID());// 审批人
			map.put("approvalState", approvepag.getApproveCondition());// 状态
			map.put("applicant", applicant==null?"":applicant);// 申请名称
			map.put("rPerson", rPerson==null?"":rPerson);// 负责人
			map.put("auditType", auditType==null?"":auditType);// 申请类型
			map.put("pCategory", pCategory==null?"":pCategory);// 产品类别
			map.put("assumePercentage", assumePercentage==null?"":assumePercentage);// 承担百分比
			array.add(map);
		}
		response.setContentType("text/json; charset=UTF-8");
		InteractiveUtil.WriteJsonForPage(array, page, response);

	}

	@RequestMapping("/findContract") // 审核表信息
	public void findContract(String approveId, HttpServletResponse response) {
		String id = approveId.trim();
		// 审批
		Approve approve = approveService.findById(Integer.valueOf(id));
		// 审核表
		Audits auditsList = auditsService.findById(Integer.valueOf(approve.getAuditId()));
		// 产品类别
		List<Salestage> salestages = salestageService.listAll();
		for (Salestage arraySalestage : salestages) {
			String salestage = arraySalestage.getSaleStageId().toString();
			if (salestage.equals(auditsList.getpCategory())) {
				auditsList.setpCategory(arraySalestage.getSaleStageName());
			}
		}
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
		String approveTime = null;
		if (approve.getApproveTime() != null) {
			approveTime = simpleDateFormat.format(approve.getApproveTime());
		}
		if (auditsList.getSupplementals() == null || auditsList.getSupplementals().trim().isEmpty()) {
			auditsList.setSupplementals("没文件!");
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("pCategory", auditsList.getpCategory());// 产品类别
		map.put("rPerson", auditsList.getrPerson());// 负责人
		map.put("approveOpinion", approve.getApproveOpinion());// 审批意见
		map.put("remarks", approve.getRemarks());// 说明
		map.put("approveTime", approveTime); // 审批时间
		map.put("Applicant", auditsList.getApplicant());// 申请单位
		map.put("effectTimeStart", auditsList.getEffectTimeStart());// 生效时间初
		map.put("effectTimeFinish", auditsList.getEffectTimeFinish());// 生效时间末
		map.put("auditType", auditsList.getAuditType());// 申请类型
		map.put("assumePercentage", auditsList.getAssumePercentage());// 承担百分比
		map.put("deposit", auditsList.getDeposit());// 保证金
		map.put("depositPattern", auditsList.getDepositPattern());// 保证金模式
		map.put("remarksremarks", auditsList.getRemarks());// 说明
		map.put("supplementals", auditsList.getSupplementals());// 附加协议
		map.put("supplementalsTwo", auditsList.getSupplementalsTwo());// 附加协议
		map.put("submitTime", auditsList.getSubmitTime());// 提交时间
		map.put("approveTailId", auditsList.getApproveTailId());// 审批类型
		map.put("approvalState", auditsList.getApprovalState());// 审核状态
		map.put("senderId", auditsList.getSenderId());// 申请人
        map.put("auditId", auditsList.getAuditId().toString()); //合同编号
        map.put("signTime", auditsList.getSignTime()); //签约时间
		JSONArray jsonArray = JSONArray.fromObject(map);
		response.setContentType("text/json; charset=UTF-8");
		try {
			response.getWriter().write(jsonArray.toString());
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 总页数,页码
	 * 
	 * @param staff
	 * @param file
	 * @return
	 */
	@RequestMapping("/count")
	public ModelAndView count(PageUtil page, HttpServletResponse response, HttpServletRequest request, String pageSize,
			String condition) {
		ModelAndView modelAndView = new ModelAndView();
		Staff staff = ((Staff) request.getSession().getAttribute("staff"));
		if (condition == null) {
			condition = "";
		}
		page.setPageSize(5);
		if (!"".equals(condition)) {
			if ("0".equals(pageSize)) { // 未审批
				Integer count = approveService.timeFindCountAudits(staff.getStaff_name(), condition.trim());//
				page.setRowCount(count);
				modelAndView.addObject("PageCount", page.getPageCount());
				modelAndView.addObject("PageNum", page.getPageNum());
				modelAndView.addObject("condition", condition);
				modelAndView.setViewName("forward:/pages/htshenhe.jsp");
				return modelAndView;
			} else if ("1".equals(pageSize)) {// 已审批，审批失败
				Integer count = approveService.timeFindCountAuditsOne(staff.getStaff_name(), condition.trim());//
				page.setRowCount(count);
				modelAndView.addObject("PageCount", page.getPageCount());
				modelAndView.addObject("PageNum", page.getPageNum());
				modelAndView.addObject("condition", condition);
				modelAndView.setViewName("forward:/pages/yihtshenhe.jsp");
				return modelAndView;
			} else if ("2".equals(pageSize)) {// 已审批，审批失败所有
				Integer count = approveService.timefindCountAllApproveCondition(condition.trim());//
				page.setRowCount(count);
				modelAndView.addObject("PageCount", page.getPageCount());
				modelAndView.addObject("PageNum", page.getPageNum());
				modelAndView.addObject("condition", condition);
				modelAndView.setViewName("forward:/pages/kaihushenpi.jsp");
				return modelAndView;
			} else {// 领导审批
				Integer count = approveService.timeTApproveCountAudits(staff.getStaff_id().toString(), condition.trim());//
				page.setRowCount(count);
				modelAndView.addObject("PageCount", page.getPageCount());
				modelAndView.addObject("PageNum", page.getPageNum());
				modelAndView.addObject("condition", condition);
				modelAndView.setViewName("forward:/pages/inhtshenhe.jsp");
				return modelAndView;
			}

		} else {
			if ("0".equals(pageSize)) { // 未审批
				Integer count = approveService.findCountAudits(staff.getStaff_name());//
				page.setRowCount(count);
				modelAndView.addObject("PageCount", page.getPageCount());
				modelAndView.addObject("PageNum", page.getPageNum());
				modelAndView.addObject("condition", condition);
				modelAndView.setViewName("forward:/pages/htshenhe.jsp");
				return modelAndView;
			} else if ("1".equals(pageSize)) {// 已审批，审批失败
				Integer count = approveService.findCountAuditsOne(staff.getStaff_name());//
				page.setRowCount(count);
				modelAndView.addObject("PageCount", page.getPageCount());
				modelAndView.addObject("PageNum", page.getPageNum());
				modelAndView.addObject("condition", condition);
				modelAndView.setViewName("forward:/pages/yihtshenhe.jsp");
				return modelAndView;
			} else if ("2".equals(pageSize)) {// 已审批，审批失败所有
				Integer count = approveService.findCountAllApproveCondition();//
				page.setRowCount(count);
				modelAndView.addObject("PageCount", page.getPageCount());
				modelAndView.addObject("PageNum", page.getPageNum());
				modelAndView.addObject("condition", condition);
				modelAndView.setViewName("forward:/pages/kaihushenpi.jsp");
				return modelAndView;
			} else {// 领导审批
				Integer count = approveService.tApproveCountAudits(staff.getStaff_id().toString());//
				page.setRowCount(count);
				modelAndView.addObject("PageCount", page.getPageCount());
				modelAndView.addObject("PageNum", page.getPageNum());
				modelAndView.addObject("condition", condition);
				modelAndView.setViewName("forward:/pages/inhtshenhe.jsp");
				return modelAndView;
			}
		}
	}

	/**
	 * 更新
	 */
	@RequestMapping("/update")
	public ModelAndView update(Audits audits) {
		ModelAndView modelAndView = new ModelAndView();
		if(audits.getAuditId()==null) {
			modelAndView.setViewName("forward:/audits/count.action?pageSize=2");
			return modelAndView;
		}
		boolean r = false;
		try {
			r = auditsService.updateAll(audits);
		} catch (Exception e) {
			logger.error("开户审批更新出错!");
		}
		if (!r) {
			modelAndView.addObject("show", "更新失败!");
			logger.error("开户审批更新失败!");
		} else {
			modelAndView.addObject("show", "更新成功!");
		}
		modelAndView.setViewName("forward:/audits/count.action?pageSize=2");
		return modelAndView;
	}

	/**
	 * 删除 id:审批表ID
	 */
	@RequestMapping("/delect")
	public ModelAndView delect(String id,String pageNums) {
		ModelAndView modelAndView = new ModelAndView();
		Approve approve = approveService.findById(Integer.valueOf(id));
		ApproveTail approveTail = apperoveTailService.findById(Integer.valueOf(approve.getApproveRoleId()));
		if (approveTail.getApproverId() != null && !"".equals(approveTail.getApproverId())) {
			String[] approverid = approveTail.getApproverId().split(",");
			String approveridArray = "";
			for (int i = 0; i < approverid.length; i++) {
				if (!approverid[i].equals(approve.getApproverID())) {
					if ("".equals(approveridArray)) {
						approveridArray = approverid[i];
					} else {
						approveridArray += "," + approverid[i];
					}
				}
			}
			approveTail.setApproverID(approveridArray);
			try {
				apperoveTailService.update(approveTail);
			} catch (Exception e) {
				logger.error("AuditsController----------------->>delect:update出错");
				e.printStackTrace();
			}
		} else {
			 int sun=approveService.findAppoveAuditsSun(approve.getAuditId());
			  if(sun<=1) {
				  auditsService.delete(Integer.valueOf(approve.getAuditId()));
			  }
		}
		boolean r = approveService.delete(Integer.valueOf(id));
		if (!r) {
			modelAndView.addObject("show", "删除失败!");
			logger.error("合同审核删除失败!");
		} else {
			modelAndView.addObject("show", "删除成功!");
		}
		modelAndView.setViewName("forward:/audits/count.action?pageSize=2&pageNum="+pageNums);
		return modelAndView;
	}

	/**
	 * 导出
	 */
	@RequestMapping("/downlaodExecls")
	public void downlaodExecls(HttpServletResponse response) {
		List<Audits> audits = auditsService.listAll();
		for (Audits auditss : audits) {
			List<Salestage> salestages = salestageService.listAll();
			for (Salestage arraySalestage : salestages) {
				String salestage = arraySalestage.getSaleStageId().toString();
				if (salestage.equals(auditss.getpCategory())) {
					auditss.setpCategory(arraySalestage.getSaleStageName());
				}
			}
		}
		String headers[] = { "AuditType", "pCategory", "Applicant", "rPerson", "EffectTimeStart", "EffectTimeFinish",
				"Deposit", "AssumePercentage", "DepositPattern","SignTime"};
		List<String> list1 = new ArrayList<String>();
		List<String> list2 = new ArrayList<String>();
		List<String> list3 = new ArrayList<String>();
		List<String> list4 = new ArrayList<String>();
		List<String> list6 = new ArrayList<String>();
		List<String> list8 = new ArrayList<String>();
		List<String> list9 = new ArrayList<String>();
		List<String> list10 = new ArrayList<String>();
		List<String> list11 = new ArrayList<String>();
		list1.add("申请类型");
		list2.add("产品类别");
		list3.add("单位名称");
		list4.add("负责人");
		list6.add("生效时间初");
		list6.add("生效时间末");
		list8.add("保证金");
		list9.add("承担百分比");
		list10.add("保证金模式");
		list11.add("签约时间");
		Map<String, Object> headerMap = new LinkedHashMap<String, Object>();
		headerMap.put("申请性质", list1);
		headerMap.put("产品类别", list1);
		headerMap.put("单位名称", list1);
		headerMap.put("负责人", list1);
		headerMap.put("生效时间初", list1);
		headerMap.put("生效时间", list1);
		headerMap.put("保证金", list1);
		headerMap.put("承担百分比", list1);
		headerMap.put("保证金模式", list1);
		headerMap.put("签约时间", list1);
		DownlaodExcel.excel(response, audits, "合同审核详情表", headerMap, headers);

	}

}
